//
//  GAOHomeController.swift
//  Weibo28
//
//  Created by 高辰 on 16/5/10.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

let ReuseIdentifier = "cellReuseIdentifier"

class GAOHomeController: GAOVisitorController {
    
    private lazy var statuesListViewModel: GAOStatusesListViewModel = GAOStatusesListViewModel()
    //  上拉加载视图
    private lazy var pullUpView: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        view.color = UIColor.redColor()
        return view
    }()
    //下拉刷新视图
    private lazy var refreshView: GAORefreshControl = {
        let control = GAORefreshControl()
        //        view.backgroundColor = UIColor.orangeColor()
        control.addTarget(self, action: "refreshDate", forControlEvents: .ValueChanged)
        return control
    }()
    
    //更新微博提示视图
    private lazy var tipLabel: UILabel = {
        let label = UILabel(textColor: UIColor.whiteColor(), fontSize: 12)
        label.textAlignment = .Center
        label.backgroundColor = UIColor.orangeColor()
        label.hidden = true
        return label
    }()
    //是否显示更新微博提示视图
    var isShowTip: Bool = false
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if loginMark == false {
            //用户未登录,进入访客视图
            visitorView?.setVistorInfo(nil, imageName: nil)
            
        } else {
            setupTipView()
            setupTableViewUI()
            loadStatusesData()
        }
    }
    
    private func setupTableViewUI() {
        
        tableView.addSubview(refreshView)
        //注册cell
        tableView.registerClass(GAOStatusesCell.self, forCellReuseIdentifier: ReuseIdentifier)
        //自动计算行高
        tableView.rowHeight = UITableViewAutomaticDimension
        //预估高度
        tableView.estimatedRowHeight = 200
        //去掉cell分割线
        tableView.separatorStyle = .None
        //  设置上拉加载更多的视图
        tableView.tableFooterView = pullUpView
        //  设置大小,防止显示出来没有留位置
        pullUpView.sizeToFit()
    }
    
    private func loadStatusesData() {
        
        //用户已登录,获取微博首页数据
        self.statuesListViewModel.requestStatuses(self.pullUpView.isAnimating(), complete: {(isSuccess, message) -> () in
            
            if self.pullUpView.isAnimating() == false && self.isShowTip == true {
                self.startTipAnimating(message)
            }
            
            //关闭上拉加载的动画
            self.pullUpView.stopAnimating()
            //结束下拉加载的刷新状态
            self.refreshView.endRefreshing()
            
            if (isSuccess == true) {
                self.tableView.reloadData()
            }
        
        })
        
    }
    
    /**
     下拉刷新数据
     */
    @objc private func refreshDate() {
        //令更新微博提示视图可以显示
        self.isShowTip = true
        //延迟加载数据
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
            
            self.loadStatusesData()
        })
    }
    
    //设置更新微博提示视图tip
    private func setupTipView() {
        if let nav = self.navigationController {
            
            tipLabel.frame = CGRect(x: 0, y: CGRectGetMaxY(nav.navigationBar.frame) - 35, width: nav.navigationBar.bounds.size.width, height: 35)
            
            nav.view.insertSubview(tipLabel, belowSubview: nav.navigationBar)
        }
    }
    
    //更新微博提示视图tip的显示与消失动画
    private func startTipAnimating(message: String) {
        //  防止执行动画时再次让其执行
        if tipLabel.hidden == false {
            return
        }
        
        //  赋值显示的内容
        tipLabel.text = message
        //  显示tiplabel
        tipLabel.hidden = false
        
        UIView.animateWithDuration(1, animations: { () -> Void in
            self.tipLabel.transform = CGAffineTransformMakeTranslation(0, self.tipLabel.frame.size.height)
            }) { (_) -> Void in
                
                UIView.animateWithDuration(1, animations: { () -> Void in
                    //  回到原始位置
                    self.tipLabel.transform = CGAffineTransformIdentity
                    
                    }, completion: { (_) -> Void in
                        self.tipLabel.hidden = true
                })
                
        }
        
    }
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


// MARK: - Table view dataSource
extension GAOHomeController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statuesListViewModel.statusesList?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! GAOStatusesCell
        cell.statusesViewModel = statuesListViewModel.statusesList![indexPath.row]
        //取消选中状态
        cell.selectionStyle = .None
        
        return cell
    }
    //将要显示cell时调用
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        //判断是否是最后一个cell
        if indexPath.row == (statuesListViewModel.statusesList!.count - 1) && !pullUpView.isAnimating() {
            //开启动画
            pullUpView.startAnimating()
            //加载数据
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                self.loadStatusesData()
            })
            
        }
    }
    
}

